<template>
  <div class="role">
     <el-row>
      <el-col :span="24">
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="4">
        <el-input placeholder="请输入角色名称" class="search-input" v-model="query" @keydown.native.enter="initList" size="medium">
          <el-button slot="append" icon="el-icon-search" @click="initList" size="medium"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="success" plain @click="addRole" size="medium">添加角色</el-button>
      </el-col>
    </el-row>
   <el-table
      class="margin-20"
      v-loading="loading"
      :data="roleList"
      border
      style="width: 100%"
      ref="refTable"
      @row-click="rowClick">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column type="expand">
         <template slot-scope="scope">
         <el-row v-for="fisrtChidern in scope.row.children" :key="fisrtChidern.id" :gutter="20">
           <template>
            <el-col :span="3">
                 <el-tag>{{fisrtChidern.text}}</el-tag>
                 <i class="el-icon-arrow-right" v-if="fisrtChidern.nodes.length !== 0"></i>
             </el-col>
             <el-col :span="21">
                <el-row v-for="secondChildren in fisrtChidern.nodes" :key="secondChildren.id">
                  <el-col :span="4">
                   <el-tag >{{secondChildren.text}}</el-tag>
                   <i class="el-icon-arrow-right" v-if="secondChildren.nodes !== null && secondChildren.nodes.length !== 0"></i>
                  </el-col>
                  <el-col :span="20">
                    <el-row>
                      <el-tag  type="warning" v-for="thirdChildren in secondChildren.nodes" :key="thirdChildren.id" v-show="thirdChildren.nodes===null || thirdChildren.nodes.length === 0">
                      {{thirdChildren.text}}
                      </el-tag>
                    </el-row>
                    <el-row v-for="thirdChildren in secondChildren.nodes" :key="thirdChildren.id">
                      <template v-if="thirdChildren.nodes!==null && thirdChildren.nodes.length !== 0">
                        <el-tag>{{thirdChildren.text}}</el-tag>
                        <i class="el-icon-arrow-right" ></i>
                        <el-tag  type="warning" v-for="child in thirdChildren.nodes" :key="child.id">
                          {{child.text}}
                        </el-tag>
                      </template>
                      <!-- <template v-if="thirdChildren.nodes===null || thirdChildren.nodes.length === 0">
                        <el-tag  type="warning">{{thirdChildren.text}}</el-tag>
                      </template> -->
                    </el-row>
                  </el-col>
                </el-row>
                <!-- <el-row v-for="secondChildren in fisrtChidern.nodes" :key="secondChildren.id">
                <el-col :span="4">
                   <el-tag >{{secondChildren.text}}</el-tag>
                   <i class="el-icon-arrow-right" v-if="secondChildren.nodes.length !== 0"></i>
                </el-col>
                <el-col :span="20">
                   <el-tag  type="warning" v-for="thirdChildren in secondChildren.nodes" :key="thirdChildren.id">
                      {{thirdChildren.text}}
                   </el-tag>
                </el-col>
                </el-row> -->
             </el-col>
           </template>
         </el-row>
         <el-row v-if="scope.row.children.length === 0">
            <el-col :span="24">该角色没有分配权限</el-col>
         </el-row>
      </template>
      </el-table-column>
      <el-table-column
        prop="RoleName"
        label="角色名称"
        width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain icon="el-icon-edit"  @click="showEditDialog(scope.row)"></el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="showDeleteDialog(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogFormVisible" width="30%">
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1"></el-step>
        <el-step title="步骤 2"></el-step>
        <el-step title="步骤 3"></el-step>
      </el-steps>
      <el-tabs v-model="activeName" @tab-click="handleClick" tab-position="left" class="mt-20">
      <el-tab-pane label="基本信息" name="first">
        <el-form :model="addRoleForm" label-width="80px" :rules="rules" ref="addRoleForm" class="mt-20" size="medium">
         <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="addRoleForm.roleName" auto-complete="off" class="search-input"></el-input>
         </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="菜单功能" name="second">
        <el-tree :data="menuList" show-checkbox node-key="id" :props="menuProps" ref="menutree"></el-tree>
      </el-tab-pane>
      <el-tab-pane label="组织机构" name="third">
        <el-tree :data="orgList" show-checkbox :default-expand-all="defaultExpand" node-key="id" :props="orgProps" ref="orgtree"></el-tree>
      </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit('addRoleForm')" size="medium">确 定</el-button>
      </div>
    </el-dialog>
     <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogFormVisible" width="30%">
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1"></el-step>
        <el-step title="步骤 2"></el-step>
        <el-step title="步骤 3"></el-step>
      </el-steps>
      <el-tabs v-model="activeName" @tab-click="handleClick" tab-position="left" class="mt-20">
      <el-tab-pane label="基本信息" name="first">
        <el-form :model="editRoleForm" label-width="80px" :rules="rules" ref="editRoleForm" class="mt-20" size="medium">
         <el-form-item label="角色名称" prop="roleName">
           <el-input v-model="editRoleForm.roleName" auto-complete="off" class="search-input"></el-input>
         </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="菜单功能" name="second">
        <el-tree :data="menuList" show-checkbox node-key="id" :props="menuProps" ref="editmenutree" :default-checked-keys="checkedMenus"></el-tree>
      </el-tab-pane>
      <el-tab-pane label="组织机构" name="third">
        <el-tree :data="orgList" show-checkbox :default-expand-all="defaultExpand" node-key="id" :props="orgProps" ref="editorgtree" :default-checked-keys="checkedOrgs"></el-tree>
      </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="editRoleSubmit('editRoleForm')" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getMenuList, getRoleList, checkRoleName, getOrgTree, addRole, editRole, deleteRole } from '@/api'
export default {
  data () {
    var validateRoleName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入角色名'))
      }
      setTimeout(() => {
        checkRoleName({ params: { txt: value, id: this.roleid } }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              callback(new Error('角色名已经存在'))
            } else {
              callback()
            }
          } else {
            callback(new Error('角色名验证失败'))
          }
        })
      }, 500)
    }
    return {
      active: 0,
      activeName: 'first',
      loading: true,
      query: '',
      total: 0,
      pagesize: 10,
      pagenum: 1,
      roleList: [],
      roleid: '',
      addDialogFormVisible: false,
      addRoleForm: {
        roleName: '',
        menuFuns: [],
        orgUsers: []
      },
      editDialogFormVisible: false,
      editRoleForm: {
        id: '',
        roleName: '',
        menuFuns: [],
        orgUsers: []
      },
      // 添加用户的表单验证
      rules: {
        roleName: [
          { required: true, validator: validateRoleName, trigger: 'blur' }
        ]
      },
      menuList: [],
      menuProps: {
        children: 'nodes',
        label: 'text'
      },
      orgList: [],
      orgProps: {
        children: 'nodes',
        label: 'text'
      },
      defaultExpand: true,
      checkedMenus: [],
      checkedOrgs: []
    }
  },
  created () {
    this.initList()
  },
  methods: {
    searchChild (val) {
      console.log(val)
      // let arr = []
      // if (val.nodes===null || val.nodes.length === 0) {
      //   arr.push(val)
      // }
      // return arr
    },
    handleClick (tab, event) {
      switch (tab.name) {
        case 'first':
          this.active = 0
          break
        case 'second':
          this.active = 1
          break
        case 'third':
          this.active = 2
          break
        default:
          this.active = 0
          break
      }
    },
    handleSizeChange (val) {
      this.pagesize = val
      this.initList()
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.initList()
    },
    // 初始化表格数据
    initList () {
      this.loading = true
      // getRoleList({ params: { RoleName: this.query, page: this.pagenum, rows: this.pagesize } }).then(res => {
      //   if (res.code === 200) {
      //     this.roleList = res.data
      //     this.total = res.data.length
      //     this.loading = false
      //   }
      // })
      this.roleList = []
      getRoleList().then(res => {
        if (res.code === 200) {
          // this.roleList = res.data
          this.total = res.data.length
          this.loading = false
          Array.from(res.data).forEach(item => {
            let children = []
            Array.from(item.tree).forEach(tree => {
              children.push(tree)
            })
            // let children = this.handelDataText(item.tree)
            this.roleList.push({
              ID: item.role.ID,
              RoleName: item.role.RoleName,
              children: children
            })
          })
          console.log(this.roleList)
        }
      })
    },
    addRole () {
      this.addDialogFormVisible = true
      this.resetForm('addRoleForm')
      this.active = 0
      this.activeName = 'first'
      getMenuList(0).then(res => {
        this.menuList = res.data
      })
      getOrgTree(0).then(res => {
        this.orgList = res.data
      })
    },
    // 新增角色保存
    addRoleSubmit (formName) {
      this.$refs[formName].validate(valide => {
        if (valide) {
          this.addRoleForm.menuFuns = this.$refs.menutree.getCheckedKeys().concat(this.$refs.menutree.getHalfCheckedKeys())
          this.addRoleForm.orgUsers = this.$refs.orgtree.getCheckedKeys().concat(this.$refs.orgtree.getHalfCheckedKeys())
          // 执行添加角色方法
          addRole(this.addRoleForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '创建角色成功'
              })
              this.addDialogFormVisible = false
              this.initList()
            }
          })
        }
      })
    },
    // 显示编辑用户对话框
    showEditDialog (row) {
      this.editDialogFormVisible = true
      this.resetForm('editRoleForm')
      this.active = 0
      this.activeName = 'first'
      this.editRoleForm.roleName = row.RoleName
      this.roleid = row.ID
      this.editRoleForm.id = row.ID
      getMenuList(row.ID).then(res => {
        this.menuList = res.data
        if (res.data.length > 0) {
          let checkmenus = this.handelData(res.data)
          this.$refs.editmenutree.setCheckedKeys(checkmenus)
        }
      })
      getOrgTree(row.ID).then(res => {
        this.orgList = res.data
        if (res.data.length > 0) {
          let checkorgs = this.handelData(res.data)
          this.$refs.editorgtree.setCheckedKeys(checkorgs)
        }
      })
    },
    // 编辑角色保存
    editRoleSubmit (formName) {
      this.$refs[formName].validate(valide => {
        if (valide) {
          this.editRoleForm.menuFuns = this.$refs.editmenutree.getCheckedKeys().concat(this.$refs.editmenutree.getHalfCheckedKeys())
          this.editRoleForm.orgUsers = this.$refs.editorgtree.getCheckedNodes().concat(this.$refs.editorgtree.getHalfCheckedKeys())
          console.log(this.editRoleForm.menuFuns)
          // 执行添加角色方法
          editRole(this.editRoleForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '编辑角色成功'
              })
              this.editDialogFormVisible = false
              this.initList()
            }
          })
        }
      })
    },
    showDeleteDialog (row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除角色操作
        deleteRole(row.ID).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handelData (data) {
      let _this = this
      let tmp = []
      Array.from(data).forEach(function (record) {
        if (record.nodes && record.nodes.length > 0) {
          let nodes = _this.handelData(record.nodes)
          tmp = tmp.concat(nodes)
        } else {
          if (record.checked === true) {
            tmp.push(record.id)
          }
        }
      })
      return tmp
    },
    // expandChange (row, expandedRows) {
    //   console.log('expand')
    //   if(this.expands.indexOf(row.id)>=0){
    //     //收起当前行
    //     this.expands.shift()
    //     return
    //   }
    //   let _this = this
    //   _this.expands.shift()
    //   _this.expands.push(row.ID)
    //   if (expandedRows.length > 1) {
    //     //只展开当前选项
    //     expandedRows.shift()
    //   }
    // },
    rowClick (row, index, e) {
      // this.$refs.refTable.toggleRowExpansion(row)
    },
    resetForm (formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    }
  }
}
</script>
<style lang="scss">
.el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
.role {
  .mt-20 {
    margin-top: 50px
  }
  .margin-20 {
    margin: 20px 0;
  }
  .search-input {
    // width: 300px;
  }
  .page {
    padding: 5px 0;
    background-color: #D3DCE6;
  }
  .el-dialog {
    display: flex;
    flex-direction: column;
    >.el-dialog__body {
      height: 500px;
      overflow: auto;
    }
  }
}
</style>
